package com.qing.springcloud.config;

import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.PropertyAccessor;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;

/**
 * @author caozhipeng
 * @date 2025/7/21
 */
@Configuration
public class RedisConfig {


    @Bean
    public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory redisConnectionFactory) {

        //JSON 序列化

        ObjectMapper om=new ObjectMapper();
        om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
        om.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);

        Jackson2JsonRedisSerializer jsonRedisSerializer=new Jackson2JsonRedisSerializer(om,Object.class);

        StringRedisSerializer stringRedisSerializer=new StringRedisSerializer();

        RedisTemplate<String, Object> template = new RedisTemplate<>();
        //hashkey 采用String的序列化方式
        template.setHashKeySerializer(stringRedisSerializer);
        //Value 序列化采用JackJson
        template.setValueSerializer(jsonRedisSerializer);
        //key采用String的序列化方式
        template.setKeySerializer(stringRedisSerializer);


        template.setConnectionFactory(redisConnectionFactory);
        return template;
    }
}
